<?php
$FIELDS = fields::getInstance();
if(empty($id) || ($f = $FIELDS->getField($id)) == FALSE)
{
   exit();
}

if(empty($_FILES) && empty($_POST['path']) && !empty($_GET['container']) && preg_match('/^[\w\d-_]+$/i', $_GET['container']))
{
   $container = $_GET['container'];
   
   ?>
<script type="text/javascript">
   $(document).ready(function() {
      $('#file_upload').uploadify({
         'uploader'  : '/tpa/swf/uploadify.swf',
         'script'    : '/admin/thumbnailing.php',
         'scriptData': {'meccanoSession': '<?php echo session_id(); ?>', 'id': <?php echo $f->id; ?>},
         'cancelImg' : '/tpa/img/uploadify/cancel.png',
         'fileExt'     : '*.jpg;*.png',
         'auto'      : true,
         'onComplete'  : function(event, ID, fileObj, response, data) {
            if($('#cropperContainer > *').size() == 0)
            {
               $('#cropperContainer').html(response);
            } else
            {
               var selected = $('#cropperContainer').tabs('option', 'selected');
               $('#crop_'+selected).html(response);
               var index = 'crop_'+ selected;
               imageParams[index].rendered = false;
               renderJCrop(index);
               var img_path = $('#crop_'+ selected +'_image').attr('src');
               if(document.getElementById('path_'+ selected))
               {
                  $('#path_'+selected).val(img_path);
               } else
               {
                  $('#CropResultsForm').prepend('<input type="hidden" id="path_'+selected+'" name="path['+selected+']" value="'+img_path+'" />');
               }
            }
         }
      });
      $('#imageSaveBtn button').button().click(function(){
         if($('#CropResultsForm').is('form'))
         {
            var v = $('#CropResultsForm').serialize();
            $('#<?php echo $container; ?> input[type=hidden]').val(v);
            $.post("/admin/thumbnailing.php", v, function(data){
               $('#<?php echo $container; ?> img').css('display', 'none');
               $('#<?php echo $container; ?>').prepend('<img src="'+ data.path +'?<?php echo time(); ?>" width="'+data.width+'" height="'+data.height+'" alt="" id="img_<?php echo $f->alias; ?>" />');
               $('#<?php echo $container; ?> span[rel=del_img]').css('display','');
               $('#cropperContainer').parent().remove();
            }, "json");
         } else
         {
            var $alert = $('<div><?php echo gettext::translate('meccano', 'no_images'); ?></div>');
            $alert.dialog({
               modal: true,
               resizable:false,
               buttons: {Ok: function() {$(this).dialog( "destroy" );}}
            });
         }
      });
   });
</script>
   
<div id="uploadContainer" class="fl-left"><input id="file_upload" name="file_upload" type="file" /></div>
<div id="imageSaveBtn" class="fl-right" style="padding: 10px 10px 0 0;"><button><?php echo gettext::translate('meccano','save'); ?></button></div>
<div class="clear"></div>
<div id="cropperContainer">
</div>
   <?php
} elseif(empty($_POST['path']))
{
   if($_FILES['Filedata']['error'] == 0
           && ($fileinfo = getimagesize($_FILES['Filedata']['tmp_name']))
           && ($fileinfo[2] == 1 || $fileinfo[2] == 2 || $fileinfo[2] == 3))
   {

      switch ($fileinfo[2])
      {
         case 1:
            $ext = '.gif';
            break;
         case 2:
            $ext = '.jpg';
            break;
         case 3:
            $ext = '.png';
            break;
      }

      $image = uploadfile((microtime(1) * 10000) . $ext, ROOT . TMP_FOLDER, $_FILES['Filedata']['tmp_name']);
      if ($image != FALSE)
      {
         $image_path = ROOT . TMP_FOLDER . '/' . $image;
         $rel_path   = TMP_FOLDER . '/' . $image;

         $width  = 300;
         $height = 300;
         foreach($f->images AS $params)
         {
            if($width < $params['max_w'])
               $width  = $params['max_w'];
            if($height < $params['max_h'])
               $height = $params['max_h'];
         }
         $width = ceil($width * 1.3);
         $height = ceil($height * 1.3);

         if($fileinfo[0] > $width && $fileinfo[1] > $height)
         {
            $image = resize_iMagick($image_path, $image_path, $width, $height, 1);
         } else
         {
            unset($image);
            $image['width'] = $fileinfo[0];
            $image['height'] = $fileinfo[1];
         }
         $image['path'] = $rel_path;

         if(isset($_POST['tab']) && isset($f->images[$_POST['tab']]))
         {
            $params = $f->images[$_POST['tab']];
            
            echo '<div style="float:left;margin:10px 0 5px 5px;">';
            echo '<img src="'. $image['path'] .'" width="'. $image['width'] .'" height="'. $image['height'] .'" id="crop_'. $_POST['tab'] .'_image" />';
            echo '</div>';
            if($params['fixed'] == 1)
            {
               echo '<div style="float:right;width:'. $params['max_w'] .'px;height:'. $params['max_h'] .'px;overflow:hidden;margin:10px 5px 5px 0; padding:0;" align="right">';
               echo '<img src="'. $image['path'] .'" id="crop_'. $_POST['tab'] .'_preview" />';
               echo '<br /></div>';
            }
            echo '<div class="clear"></div>';
            exit();
         }

         # TABS
         echo '<ul>';
         foreach($f->images AS $key=>$params)
         {
            echo '<li><a href="#crop_'. $key .'"><span>'. $params['max_w'] .'x'. $params['max_h'] .'</span></a></li>';
         }
         echo '</ul>';

         # TABS CONTENT
         foreach($f->images AS $key=>$params)
         {
            echo '<div id="crop_'. $key .'">';
            echo '<div style="float:left;margin:10px 0 5px 5px;">';
            echo '<img src="'. $image['path'] .'" width="'. $image['width'] .'" height="'. $image['height'] .'" id="crop_'. $key .'_image" />';
            echo '</div>';
            if($params['fixed'] == 1)
            {
               echo '<div style="float:right;width:'. $params['max_w'] .'px;height:'. $params['max_h'] .'px;overflow:hidden;margin:10px 5px 5px 0; padding:0;" align="right">';
               echo '<img src="'. $image['path'] .'" id="crop_'. $key .'_preview" />';
               echo '<br /></div>';
            }
            echo '<div class="clear"></div>';
            echo '</div>';
         }

         # JS
         ?>
<script type="text/javascript">
   var imageParams = {
      <?php
      reset($f->images);
      foreach($f->images AS $key=>$params)
      {
         if($key != 0) echo ',';
         echo 'crop_'. $key .':{';
         echo 'xmin:'. ($params['min_w'] < $image['width'] ? $params['min_w'] : $image['width']) .',';
         echo 'ymin:'. ($params['min_h'] < $image['height'] ? $params['min_h'] : $image['height']) .',';
         echo 'xmax:'. $params['max_w'] .','; // ($params['max_w'] < $image['width'] ? $params['max_w'] : $image['width'])
         echo 'ymax:'. $params['max_h'] .','; // ($params['max_h'] < $image['height'] ? $params['max_h'] : $image['height'])
         echo 'ratio:'. ($params['fixed'] == 1 ? 'true' : 'false') .',';
         echo 'rendered:false}';
      }
      ?>
   };
   $(document).ready(function(){
      $('#cropperContainer').tabs({show:function(event, ui){
            var index = 'crop_'+ ui.index;
            renderJCrop(index);
         }});
   });
   function renderJCrop(index)
   {
      if(imageParams[index].rendered)
      {
         return false;
      } else
      {
         $('#'+index+'_image').Jcrop({
            onChange: eval(index+'_func'),
            onSelect: eval(index+'_func'),
            boxWidth: 700,
            boxHeight: 500,
            bgColor: 'black',
            bgOpacity: .3,
            aspectRatio: (imageParams[index].ratio ? imageParams[index].xmax/imageParams[index].ymax : false),
            minSize: [imageParams[index].xmin, imageParams[index].ymin],
            setSelect: [0,0,imageParams[index].xmin,imageParams[index].ymin]
         });
         imageParams[index].rendered = true;
      }
   }

   <?php
   reset($f->images);
   foreach($f->images AS $key=>$params)
   {
      ?>
   function crop_<?php echo $key; ?>_func(c)
   {
      $('#file_upload').uploadifySettings('scriptData', {"tab":<?php echo $key; ?>});
      <?php if($params['fixed'] == 1): ?>
      var rx = <?php echo $params['max_w']; ?> / c.w;
      var ry = <?php echo $params['max_h']; ?> / c.h;
      var w = $('#crop_<?php echo $key; ?>_image').attr('width');
      var h = $('#crop_<?php echo $key; ?>_image').attr('height');
      $('#crop_<?php echo $key; ?>_preview').css({
         width: Math.round(rx * w) + 'px',
         height: Math.round(ry * h) + 'px',
         marginLeft: '-' + Math.round(rx * c.x) + 'px',
         marginTop: '-' + Math.round(ry * c.y) + 'px'
      });
      <?php endif; ?>
      $('#crop_<?php echo $key; ?>_x').val(c.x);
      $('#crop_<?php echo $key; ?>_y').val(c.y);
      $('#crop_<?php echo $key; ?>_w').val(c.w);
      $('#crop_<?php echo $key; ?>_h').val(c.h);
   }
      <?php
   }
   ?>
</script>
<div style="display:none;">
   <form id="CropResultsForm">
      <input type="hidden" name="path[0]" id="path_0" value="<?php echo basename($rel_path); ?>" />
      <input type="hidden" name="id" value="<?php echo $f->id; ?>" />
      <?php
      reset($f->images);
      foreach($f->images AS $key=>$params)
      {
         echo '<input type="hidden" id="crop_'. $key .'_x" name="crop['. $key .'][x]" value="0" />';
         echo '<input type="hidden" id="crop_'. $key .'_y" name="crop['. $key .'][y]" value="0" />';
         echo '<input type="hidden" id="crop_'. $key .'_w" name="crop['. $key .'][w]" value="'. $params['min_w'] .'" />';
         echo '<input type="hidden" id="crop_'. $key .'_h" name="crop['. $key .'][h]" value="'. $params['min_h'] .'" />';
      }
      ?>

   </form>
</div>
         <?php
      }
   }
} else
{
   # MAKE TEMPORARY IMAGE PREVIEW
   $data = array();

   $image_0_path = is_array($_POST['path']) ? $_POST['path'][0] : $_POST['path'];
   if(file_exists(ROOT . TMP_FOLDER .'/'. basename($image_0_path)) && isset($_POST['crop'][0]))
   {
      $w = isset($_POST['crop'][0]['w']) ? intval($_POST['crop'][0]['w']) : $f->images[0]['max_w'];
      $h = isset($_POST['crop'][0]['h']) ? intval($_POST['crop'][0]['h']) : $f->images[0]['max_h'];
      $x = isset($_POST['crop'][0]['x']) ? intval($_POST['crop'][0]['x']) : 0;
      $y = isset($_POST['crop'][0]['y']) ? intval($_POST['crop'][0]['y']) : 0;

      if($w && $h)
      {
         $file_name   = ROOT . TMP_FOLDER .'/'. basename($image_0_path);
         $file_name_t = ROOT . TMP_FOLDER .'/_'. basename($image_0_path);
         $file_size   = getimagesize($file_name);
         
         if ($w < $file_size[0] || $h < $file_size[1] || $x || $y)
         {
            crop_iMagick($file_name, $file_name_t, $w, $h, $x, $y);
         }
         
         $data['width'] = $w;
         $data['height'] = $h;

         if($w > $f->images[0]['max_w'] || $h > $f->images[0]['max_h'])
         {
            $data = resize_iMagick($file_name_t, $file_name_t, $f->images[0]['max_w'], $f->images[0]['max_h'], 2);
         }

         $data['path'] = TMP_FOLDER .'/_'. basename($image_0_path);
      }
   }
   
   echo json_encode($data);
}
exit();
